import { contextBridge, ipcRenderer } from "electron";
import { electronAPI } from "@electron-toolkit/preload";

// 枚举 sql 目录，并把所有文件名放入列表返回
import fs from "fs";
import path from "path";

const parseSqlFile = (filePath: string) => {
  const content = fs.readFileSync(filePath, "utf-8");

  // 读取文件内，查找注释
  const lines = content.split("\n");
  const result = {};
  let currentKey = "";
  for (const line of lines) {
    if (line.startsWith("--")) {
      currentKey = line.slice(2).trim();
      continue;
    }
    if (!line.trim()) continue;
    result[currentKey] = (result[currentKey] || "") + line + "\n";
  }
  return result;
};

const getFiles = async () => {
  return ipcRenderer.invoke("getFiles");
}

const executeQuery = async (sql: string) => {
  return ipcRenderer.invoke("executeQuery", sql);
};

const selectPath = async (path: string) => {
  return ipcRenderer.invoke("selectPath", path || ".");
};

const setConfig = async (config: string) => {
  return ipcRenderer.invoke("setConfig", config);
};

const getConfig = async () => {
  return ipcRenderer.invoke("getConfig");
};

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
const api = {
  getFiles,
  parseSqlFile,
  executeQuery,
  selectPath,
  setConfig,
  getConfig,
};

if (process.contextIsolated) {
  // eslint-disable-line no-undef
  console.log("contextIsolated");
  try {
    contextBridge.exposeInMainWorld("electron", electronAPI);
    contextBridge.exposeInMainWorld("api", api);
  } catch (error) {
    console.error(error);
  }
} else {
  console.log("window", window);
  // @ts-ignore (define in dts)
  window.electron = electronAPI;
  // @ts-ignore (define in dts)
  window.api = api;
}
